<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
        :model="formModel"
        :rules="rules"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <!-- prefix-icon 字体图标 -->
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="formModel.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="formModel.password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
            v-model="formModel.repassword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <!-- 提交表单  调用 register 方法 -->
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="register"
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <el-form
        ref="form"
        size="large"
        autocomplete="off"
        v-else
        :model="formModel"
        :rules="rules"
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="formModel.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="formModel.password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup name="">
import { ref, watch } from 'vue'
import { Lock, User } from '@element-plus/icons-vue'
import { userRegisterService, userLoginService } from '@/api/user'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
//前面已经设置按需导入全局，这里不需要导入，重复导入会出现样式错误
// import { ElMessage } from 'element-plus'
let isRegister = ref(true)
let form = ref()

//提交的数据对象，属性名与后台对应，看接口文档https://apifox.com/apidoc/shared-26c67aee-0233-4d23-aab7-08448fdf95ff/api-93850835
const formModel = ref({
  username: '',
  password: '',
  repassword: ''
})
// 表单验证规则  不需要响应式
const rules = {
  //required  非空校验
  //trigger   校验的触发方式  blur  失去焦点时触发
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 1,
      max: 10,
      message: '长度在1到10个字符',
      trigger: 'blur'
    },
    {
      pattern: /^[a-zA-Z0-9]*$/,
      message: '用户名必须是字母或数字',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    //  \S  非空字符
    { pattern: /^\S{6,15}$/, message: '6-15位非空格字符', trigger: 'blur' }
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '6-15位非空格字符', trigger: 'blur' },
    //自定义校验
    {
      //rule  当前校验规则相关信息
      //value  所校验的表单元素目前的表单值
      //callback  回调函数  校验通过时调用  callback()  校验成功   callback(new Error('错误信息'))
      validator: (rule: any, value: any, callback: any) => {
        //判断两次是否一致
        if (value === formModel.value.password) callback()
        else callback(new Error('两次密码不一致'))
      },
      trigger: 'blur'
    }
  ]
}

//提交时  对内容进行校验
const register = async () => {
  //validate()  触发表单校验
  await form.value.validate()
  //发起请求  在api文件中封装了请求方法
  try {
    const registerRes = await userRegisterService(formModel.value)
    //弹出elementplus的提示框
    ElMessage.success(registerRes.data.message)
    setTimeout(() => {
      isRegister.value = false //切换到登录
    }, 2000)
  } catch (err: any) {
    ElMessage.error(err.response.data.message)
  }
}

//切换时重置表单内容
watch(isRegister, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: ''
  }
})

const login = async () => {
  //validate()  触发表单校验
  await form.value.validate()

  try {
    const loginRes = await userLoginService({
      username: formModel.value.username,
      password: formModel.value.password
    })

    //存token 到user的store中 使用store中提前定义好的修改方法
    userStore.setToken(loginRes.data.token)

    // console.log(loginRes)
    ElMessage.success(loginRes.data.message)

    // 跳转到首页
    setTimeout(() => {
      router.push('/')
    }, 2000)
  } catch (err: any) {
    ElMessage.error(err.response.data.message)
    console.log(err)
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
